# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: util_imgs.py
@time: 2025/3/31 10:57 
@desc: 

"""
import os
from uuid import uuid4
from PIL import Image
from io import BytesIO

class ImagesMerge(object):
    """

    """

    def __init__(self, file_list=None):
        self.file_list = file_list

    def read_img(self, file):
        """

        :param file:
        :return:
        """
        return Image.open(file)
    @staticmethod
    def get_img_date(img_file):
        """

        :param img_file:
        :return:
        """
        image_file = open(img_file, 'rb')
        image_data = BytesIO(image_file.read())
        image_file.close()
        return image_data


    def save_img(self, file, img):
        """

        :param file:
        :param img:
        :return:
        """
        return img.save(file)

    def make_merge_file(self):
        """

        :return:
        """
        save_folder = "./tmp/merge"
        os.makedirs(save_folder,exist_ok=True)
        save_file = os.path.join(save_folder, f"merge_{uuid4()}.png")
        return save_file


    def merge_imgs(self):
        """

        :return:
        """
        images = [Image.open(img_file) for img_file in self.file_list]
        widths, heights = zip(*(img.size for img in images))
        total_width = sum(widths)  # 所有图片宽度的总和
        max_height = max(heights)  # 最大的图片高度
        new_img = Image.new('RGB', (total_width, max_height))
        x_offset = 0
        for img in images:
            new_img.paste(img, (x_offset, 0))  # 每张图片依次放置
            x_offset += img.width  # 更新偏移量
        merge_file = self.make_merge_file()
        self.save_img(merge_file, new_img)
        return merge_file

if __name__ == '__main__':
    img_list = [r"D:\Project\Python\baidu\crowdtest\collection-script\CR\tests\zzprojects\img_1.png",r"D:\Project\Python\baidu\crowdtest\collection-script\CR\tests\zzprojects\img_2.png",r"D:\Project\Python\baidu\crowdtest\collection-script\CR\tests\zzprojects\img.png"]
    img = ImagesMerge(img_list)
    print(img.merge_imgs())
